package app.fugema.shop.main.setting.view;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.graphics.drawable.DrawableCompat;

import com.base.common.app.BaseConstant;
import com.base.common.app.LoginUtils;
import com.base.common.utils.CacheUtils;
import com.base.common.utils.ThreadManager;
import com.base.common.utils.UIUtils;
import com.base.common.view.base.BaseTitleActivity;
import com.base.common.viewmodel.BaseViewModel;
import com.base.common.viewmodel.RxSchedulerTransformer;
import com.jeremyliao.liveeventbus.LiveEventBus;
import app.fugema.shop.R;
import app.fugema.shop.constants.PublicGlobal;
import app.fugema.shop.databinding.SettingActivityBinding;
import app.fugema.shop.main.login.model.MUserInfo;
import app.fugema.shop.main.login.view.BindPhoneActivity;

import app.fugema.shop.main.login.view.ForgetPassWordActivity;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class SettingActivity extends BaseTitleActivity<SettingActivityBinding, BaseViewModel> implements View.OnClickListener {

    public static void start(Context context)
    {
        Intent starter = new Intent(context, SettingActivity.class);
        context.startActivity(starter);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting_activity);
    }

    @Override
    protected int getStatusBarColor()
    {
        return R.color.redColor;
    }

    @Override
    protected void initNotificationReceipt()
    {
        super.initNotificationReceipt();
        LiveEventBus.get(BaseConstant.EventKey.USER_UPDATE_SUCCESS, MUserInfo.class).observe(this, (userBean) -> {
                setViewData(userBean);
            });

    }


    private void setViewData(MUserInfo userBean)
    {
        if (userBean != null)
        {
            //binding.tvNickname.setText(userBean.getNick());
            if( UIUtils.isNotEmpty(userBean.getPhoto()) )
            {
                //binding.givHeadImage.loadUrl(userBean.getPhoto());
            }
        }
    }

    @Override
    protected void initView()
    {
        setCloseImg(R.mipmap.ic_back_white);
        setTitle("系统设置",R.color.white);
        if (PublicGlobal.initUserInfo() != null)
        {
            setViewData(PublicGlobal.getUserInfo());
        }


        binding.llBindPhone.setOnClickListener(this);
        binding.btnNotifySetting.setOnClickListener(this);
        binding.btnClearCache.setOnClickListener(this);
        binding.btnAbout.setOnClickListener(this);
        binding.btnLoginOut.setOnClickListener(this);
        binding.btnRemoveUser.setOnClickListener(this);
        //binding.flUserInfo.setOnClickListener(this);
        binding.llPayPwd.setOnClickListener(this);
        binding.llLoginPwd.setOnClickListener(this);
//        if (LoginUtils.isLogin()) {
//            binding.btnLoginOut.setVisibility(View.VISIBLE);
//        } else {
//            binding.btnLoginOut.setVisibility(View.GONE);
//        }
        showCacheSize();

    }

    private void showCacheSize() {

        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                emitter.onNext(CacheUtils.getTotalCacheSize(getActivity()));
                emitter.onComplete();
            }
        }).compose(new RxSchedulerTransformer<>()).subscribe(new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String s) {
                binding.tvCache.setText(s);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });


    }

    private void clearCache() {
        showLoad();
        ThreadManager.getSinglePool().execute(new Runnable() {
            @Override
            public void run() {
                CacheUtils.clearAllCache(getActivity());
                UIUtils.runInMainThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.tvCache.setText("0KB");
                        dismissLoad();
                    }
                });
            }
        });


//        PermissionUtils.initStoragePermission(this).subscribe(new BaseRxObserver<Boolean>() {
//            @Override
//            public void onNext(Boolean aBoolean) {
//                if (aBoolean) {
//
//                }
//            }
//        });


    }

    public void setSwitchColor(SwitchCompat v) {

        // set the thumb color
        DrawableCompat.setTintList(v.getThumbDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        0xffFFFFFF,
                        0xffFFFFFF
                }));

        // set the track color
        DrawableCompat.setTintList(v.getTrackDrawable(), new ColorStateList(
                new int[][]{
                        new int[]{android.R.attr.state_checked},
                        new int[]{}
                },
                new int[]{
                        0xff027CF7,
                        0xffE5E7E6
                }));
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_bind_phone:
                //绑定手机
                BindPhoneActivity.lunch(getActivity());
                break;
            case R.id.btnNotifySetting:
                SettingNotifyActivity.start(mContext);
                break;
            case R.id.ll_pay_pwd:
                //修改支付密码
                ModefyLoginPwdActivity.start(this,true);
                break;
            case R.id.ll_login_pwd:
                //修改登录密码
                ModefyLoginPwdActivity.start(this,false);
                break;
            case R.id.btnClearCache:
                //替换成 修改个人资料
                SettingUserDataActivity.start(getActivity());
                /*
                new AlertDialog.Builder(SettingActivity.this)
                        .setTitle("警告")
                        .setMessage("清除所有缓存?")
                        .setPositiveButton("确定",
                                new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                        clearCache();
                                    }
                                })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();
                */
                break;
            case R.id.btn_about:
                //关于页面
                AboutActivity.start(this);
                break;
            case R.id.btnLoginOut:
                LoginUtils.loginOut();
                LiveEventBus.get(BaseConstant.EventKey.LOGIN_OUT_ONCLICK).post(-1);
                finish();
                break;
            case R.id.btnRemoveUser:
                //注销先退出登录
                if (LoginUtils.isLogin())
                {
                    new AlertDialog.Builder(SettingActivity.this)
                            .setTitle("警告")
                            .setMessage("当你注销“" + UIUtils.getString(R.string.app_name) + "”帐户后，我们将删除相应的信息?")
                            .setPositiveButton("确定",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {

                                            LoginUtils.loginOut();
                                            LiveEventBus.get(BaseConstant.EventKey.LOGIN_OUT_ONCLICK).post(-1);
                                            dialog.dismiss();
                                            finish();
                                        }
                                    })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            }).show();
                }
                break;
        }
    }
}
